<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;

// import Joomla modelitem library
jimport('joomla.application.component.model');

class PmpingerModelPmpinger extends JModelLegacy
{
    protected $_changes=null;
    
    public function getBuffer()
    {
        if (is_null($this->_changes)){
            $dbo = $this->getDbo();
            
            // get buffered changes
            $query = $dbo
                ->getQuery(true)
                ->select("DISTINCT `endpoint`,`key`")
                ->from( '#__pmpinger_buffer' );
            $dbo->setQuery($query);
            $this->_changes = $dbo->loadObjectList();
            
            // Check for errors.
            if (count($errors = $this->get('Errors'))) {
                throw new Exception(implode("\n", $errors), 500);
            }
            
            // create a pmapi datadump uri foreach change
            if (!class_exists('PmapiHelperRoute'))
                require (JPATH_SITE.DS.'components'.DS.'com_pmapi'.DS.'helpers'.DS.'router.php');
            
            $base = JURI::base();
            $baseLen = strlen(JURI::base(true));
            foreach ($this->_changes as $change){
                $relativeURL = JRoute::_(PmapiHelperRoute::getDataRoute($change->endpoint,$change->key),true);
                // see http://forum.joomla.org/viewtopic.php?f=231&t=398666
                $absoluteURL = $base.substr($relativeURL, $baseLen + 1);
                $change->uri = $absoluteURL;
            }
        }
        
        return $this->_changes;
    }

    
    public function getPingerURL()
    {
        static $url = null;
        if (is_null($url)) $url = JComponentHelper::getParams('com_pmpinger')->get('pinger_url','');
        
        return $url;
    }
    
    
    public function flushBuffer()
    {
        $pingerURL = $this->getPingerURL();
        $changes=$this->getBuffer();
        
        if (empty($pingerURL)){
            $flushResult = "No pinger defined, please conctat administrator.";
        } elseif (empty($changes)){
            $flushResult = "No changes";
        } else {
            // signal changes to the pinger
            $data ='';
            foreach ($changes as $change){
                $data .= $change->uri ."\n";
            }
            
            
            jimport( 'joomla.client.http' );
            $jhttp = $jhttp = new JHttp();
            $response = $jhttp->put($pingerURL,$data);
            
            if ($response->code == 200) {
                // empty buffer
                $dbo = $this->getDbo();
                
                // delete buffered changes
                $query = $dbo
                    ->getQuery(true)
                    ->delete('#__pmpinger_buffer' );
                $dbo->setQuery($query);
                if (version_compare(JVERSION, '3.0.0', 'ge')) {
                    $dbo->execute();
                } else {
                    $dbo->query();
                }
                $this->_changes=null;
                $flushResult = $response->body;
            } else {
                $flushResult = "Error $response->code calling pinger: $response->body";
            }
        } 
                    
        return $flushResult;               
    }
}